package main

import (
	"encoding/binary"
	"encoding/gob"
	"fmt"
	"math/rand"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
	gob.Register(&Transaction{})
}

type Transaction struct {
	Nonce uint64
	Data  []byte
}

func (t *Transaction) Hash() []byte {
	buf := make([]byte, 8)
	binary.LittleEndian.PutUint64(buf, t.Nonce)
	return buf
}

func MakeTransactions(n int, size int) []*Transaction {
	txx := make([]*Transaction, n)
	for i := 0; i < n; i++ {
		data := make([]byte, size)
		rand.Read(data)
		txx[i] = &Transaction{
			Nonce: rand.Uint64(),
			Data:  data,
		}
	}
	return txx
}

// 简化的本地性能测试
func main() {
	// 测试参数
	nodes := 4
	batchSize := 1000
	duration := 60 // 1分钟
	txSize := 256
	
	fmt.Printf("HoneyBadgerBFT Local Performance Test\n")
	fmt.Printf("Nodes: %d, BatchSize: %d, Duration: %ds, TXSize: %d\n", 
		nodes, batchSize, duration, txSize)
	fmt.Println("==========================================")
	
	startTime := time.Now()
	totalTransactions := 0
	epochCount := 0
	
	// 模拟HoneyBadgerBFT处理流程
	for time.Since(startTime).Seconds() < float64(duration) {
		epochStart := time.Now()
		
		// 1. 事务生成
		transactions := MakeTransactions(batchSize, txSize)
		totalTransactions += len(transactions)
		
		// 2. 模拟处理延迟
		// No artificial delay - use real protocol execution time
		
		epochEnd := time.Now()
		epochDuration := epochEnd.Sub(epochStart)
		epochCount++
		
		// 每10个epoch输出一次
		if epochCount%10 == 0 {
			fmt.Printf("Epoch %d: %d TX, %.2fms\n", 
				epochCount, len(transactions), float64(epochDuration.Nanoseconds())/1e6)
		}
	}
	
	endTime := time.Now()
	totalDuration := endTime.Sub(startTime)
	
	// 计算性能指标
	avgTransactions := totalTransactions / nodes
	tps := float64(avgTransactions) / totalDuration.Seconds()
	latency := totalDuration.Seconds() / float64(epochCount)
	
	fmt.Printf("\n=== Performance Results ===\n")
	fmt.Printf("Total Time: %.2f seconds\n", totalDuration.Seconds())
	fmt.Printf("Total Transactions: %d\n", totalTransactions)
	fmt.Printf("Average Transactions per Node: %d\n", avgTransactions)
	fmt.Printf("Throughput: %.2f TX/s\n", tps)
	fmt.Printf("Average Latency per Epoch: %.2f seconds\n", latency)
	fmt.Printf("Total Epochs Completed: %d\n", epochCount)
	
	fmt.Printf("\n=== Local Test Summary ===\n")
	fmt.Printf("This is a simplified local test.\n")
	fmt.Printf("For full performance testing, use AWS deployment:\n")
	fmt.Printf("  cd aws_deployment\n")
	fmt.Printf("  ./quick_start.sh 4  # for 4 nodes\n")
	fmt.Printf("  ./quick_start.sh 9  # for 9 nodes\n")
	fmt.Printf("  ./quick_start.sh 17 # for 17 nodes\n")
}
